package cn.le.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 *相同点:
 *  都是接口
 *  都可用来编写多线程程序
 *  都需要调用Thread.start()启动线程
 *
 * 不同点:
 *  实现Callable接口的任务线程能返回执行结果,而实现Runnable接口任务的线程不能返回结果
 *  Callable接口的call()方法允许抛出异常,而Runnable接口的run()方法的异常不能抛出,只能在内部消化
 *
 * 注意点
 *  Callable接口支持返回执行结果,此时要调用FutureTask.get()方法来实现,此方法会阻塞主线程直到获取返回结果,
 *  当不调用此方法,线程不会阻塞
 */
public class RunnableAndCallable {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CallableImpl callable = new CallableImpl("my callable test!");
        FutureTask<String> task = new FutureTask<String>(callable);
        long beginTime = System.currentTimeMillis();

        new Thread(task).start();
        String result = task.get();

        long endTime = System.currentTimeMillis();
        System.out.println("hello : "+ result);
        System.out.println((endTime-beginTime));
    }
}


class CallableImpl implements Callable<String>{

    private String acceptStr;

    public CallableImpl(String acceptStr)
    {
        this.acceptStr = acceptStr;
    }

    @Override
    public String call() throws Exception {

        Thread.sleep(1000);

        return this.acceptStr + "append some chars and result it !";
    }
}
